<script>
import { defineComponent, onBeforeMount, reactive, ref, toRefs } from 'vue';

import dayjs from 'dayjs';

export default defineComponent({
  name: 'SearchMore',
  components: {},
  props: {
    searchContent: {
      type: Array,

      default: [],
      required: true,
    },
    rowCount: {
      type: Number,
      default: 4,
      required: false,
    },
  },
  emits: ['onSearch'],
  setup(props, { emit }) {
    const formRef = ref();
    const state = reactive({
      heightSearch: 50,
      fold: false,
      searchContent: props.searchContent,
      rowCount: props.rowCount,
      queryForm: {},
    });
    const handleFold = () => {
      state.fold = !state.fold;
      handleHeightSearch();
    };
    const handleHeightSearch = () => {
      // if (state.fold) state.heightSearch = $baseTableHeight(2) - 47;
      // else state.heightSearch = $baseTableHeight(3) - 30;
    };
    const submitForm = async () => {
      // if (!formEl) return
      for (const key in state.queryForm) {
        if (Object.hasOwnProperty.call(state.queryForm, key)) {
          const item = state.queryForm[key];
          if (Object.prototype.toString.call(item) === '[object Date]') {
            state.queryForm[key] = dayjs(item).format('YYYY-MM-DD');
          } else if (
            Object.prototype.toString.call(item) === '[object Array]'
          ) {
            // 下拉框多选 以及 开始时间结束时间
            if (
              item[0] &&
              Object.prototype.toString.call(item[0]) === '[object Date]' &&
              isTimeFormat([
                ...dayjs(item[0]).format('YYYY-MM-DD'),
                ' 00:00:00',
              ])
            ) {
              // 时间格式数据
              item[0] = [...dayjs(item[0]).format('YYYY-MM-DD'), ' 00:00:00'];
              item[1] = [...dayjs(item[1]).format('YYYY-MM-DD'), ' 23:59:59'];
              state.queryForm[key] = item.join(',') || null;
            } else {
              // 下拉框格式数据
              state.queryForm[key] = item.join(',') || null;
            }
          }
        }
      }
      await emit('onSearch', state.queryForm);
      for (const key in state.queryForm) {
        if (Object.hasOwnProperty.call(state.queryForm, key)) {
          const obj = state.searchContent.find((i) => i.value === key);
          const item = state.queryForm[key];
          if (item && typeof item === 'string' && item.includes(',')) {
            // 涉及到了 多选都走了这个
            state.queryForm[key] = item.split(',');
          }
          if (
            obj &&
            obj.type === 'Select' &&
            obj.multiple &&
            item &&
            !item.includes(',')
          ) {
            // 下拉框多选 但是只选了一个
            state.queryForm[key] = (item && [item]) || null;
          }
        }
      }
    };
    const isTimeFormat = (str) => {
      return /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(str);
    };
    const getSearch = (row) => {
      const s = (row - 1) * state.rowCount;
      const e = Math.min(s + state.rowCount, state.searchContent.length);
      const list = [];
      for (let i = s; i < e; i++) {
        list.push(state.searchContent[i]);
      }
      return list;
    };
    const getColSpan = () => {
      let colSpan = 5;
      switch (Number.parseInt(state.rowCount)) {
        case 1: {
          colSpan = 18;
          break;
        }
        case 2: {
          colSpan = 9;
          break;
        }
        case 3: {
          colSpan = 6;
          break;
        }
        case 4: {
          colSpan = 5;
          break;
        }
      }
      return colSpan;
    };
    const resetForm = () => {
      init();
      emit('onSearch', state.queryForm);
    };
    onBeforeMount(() => {
      init();
    });
    const init = () => {
      props.searchContent.map((i) => {
        if (i?.value) {
          state.queryForm[i?.value] = getDefaultValue(i?.defaultValue);
        }
      });
    };
    const getDefaultValue = (v) => {
      let result = v;
      switch (v) {
        case 'day[1]': {
          result = [
            `${dayjs(new Date()).format('YYYY-MM-DD')} 00:00:00`,
            `${dayjs(new Date()).format('YYYY-MM-DD')} 23:59:59`,
          ];
          break;
        }
        case 'day[7]': {
          result = [
            `${dayDate(7)} 00:00:00`,
            `${dayjs(new Date()).format('YYYY-MM-DD')} 23:59:59`,
          ];
          break;
        }
        case 'day[30]': {
          result = [
            `${dayDate(30)} 00:00:00`,
            `${dayjs(new Date()).format('YYYY-MM-DD')} 23:59:59`,
          ];
          break;
        }
        default: {
          result = v;
          break;
        }
      }
      return result;
    };
    const dayDate = (day) => {
      return dayjs(
        new Date(new Date().setDate(new Date().getDate() - day)),
      ).format('YYYY-MM-DD');
    };

    return {
      ...toRefs(state),
      handleFold,
      resetForm,
      submitForm,
      formRef,
      dayjs,
      getSearch,
      getColSpan,
    };
  },
});
</script>
<template>
  <div class="searchHead" style="width: 100%; margin-bottom: 6px">
    <el-form
      ref="formRef"
      :model="queryForm"
      inline
      label-suffix="："
      style="width: 100%"
      @submit.prevent
    >
      <el-row
        v-for="row_index in parseInt(searchContent.length / rowCount) + 1"
        :key="row_index"
        :gutter="4"
        align="middle"
        type="flex"
      >
        <el-col
          v-for="(item, index) in getSearch(row_index)"
          :key="index"
          :span="getColSpan()"
        >
          <div class="row-flex-line-start">
            <span :class="item.label_align ? `label-n${item.label_align}` : ''">
              {{ item.label }}：
            </span>
            <el-input
              v-if="item.type === 'Input'"
              v-model="queryForm[item.value]"
              clearable
              placeholder="请输入"
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="queryForm[item.value]"
              :multiple="item.multiple"
              clearable
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="m in item.options"
                :key="m.value"
                :disabled="m.disabled"
                :label="m.label"
                :value="m.value"
              />
            </el-select>
            <el-tree-select
              v-if="item.type === 'SelectTree'"
              v-model="queryForm[item.value]"
              :check-strictly="item.check"
              :data="item.options"
              :multiple="item.multiple"
              :props="
                item.defaultProps || {
                  children: 'children',
                  label: 'name',
                  value: 'id',
                }
              "
              :render-after-expand="false"
              clearable
              default-expand-all
              filterable
              node-key="id"
              placeholder="请选择"
              style="width: 100%"
            />
            <!--              :filter-node-method="(value, data) => data.label.includes(value)"-->
            <el-date-picker
              v-if="item.type === 'DatePicker'"
              v-model="queryForm[item.value]"
              placeholder="请选择日期"
              type="date"
            />
            <el-date-picker
              v-if="item.type === 'DatePickers'"
              v-model="queryForm[item.value]"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD"
            />
            <el-date-picker
              v-if="item.type === 'DatePickerYear'"
              v-model="queryForm[item.value]"
              placeholder="请选择年度"
              style="width: 336px"
              type="year"
              value-format="YYYY"
            />
            <el-date-picker
              v-if="item.type === 'DatePickerMonth'"
              v-model="queryForm[item.value]"
              placeholder="请选择月份"
              style="width: 336px"
              type="month"
              value-format="YYYY-MM"
            />
          </div>
        </el-col>
        <el-col v-if="row_index === 1" :span="4">
          <div class="row-flex-line-start">
            <el-button
              v-if="searchContent.length > 0"
              icon="Search"
              native-type="submit"
              type="primary"
              @click="submitForm(formRef)"
            >
              查询
            </el-button>
            <el-button
              v-if="searchContent.length > 0"
              icon="RefreshLeft"
              @click="resetForm(formRef)"
            >
              重置
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
